3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Database abstraction object
33 abstract class DatabaseBase
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
66 /** @var BagOStuff APC cache */
68 /** @var LoggerInterface */
69 protected $connLogger;
70 /** @var LoggerInterface */
71 protected $queryLogger;
72 /** @var callback Error logging callback */
73 protected $errorLogger;
75 /** @var resource Database connection */
76 protected $mConn = null;
78 protected $mOpened = false;
80 /** @var array[] List of (callable, method name) */
81 protected $mTrxIdleCallbacks = [];
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxPreCommitCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxEndCallbacks = [];
86 /** @var array[] Map of (name => (callable, method name)) */
87 protected $mTrxRecurringCallbacks = [];
88 /** @var bool Whether to suppress triggering of transaction end callbacks */
89 protected $mTrxEndCallbacksSuppressed = false;
92 protected $mTablePrefix;
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
112 protected $delimiter = ';';
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
120 protected $mTrxLevel = 0;
122 * Either a short hexidecimal string if a transaction is active or ""
125 * @see DatabaseBase::mTrxLevel
127 protected $mTrxShortId = '';
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
134 * @see DatabaseBase::mTrxLevel
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
144 * @see DatabaseBase::mTrxLevel
146 private $mTrxFname = null;
148 * Record if possible write queries were done in the last transaction started
151 * @see DatabaseBase::mTrxLevel
153 private $mTrxDoneWrites = false;
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
158 * @see DatabaseBase::mTrxLevel
160 private $mTrxAutomatic = false;
162 * Array of levels of atomicity within transactions
166 private $mTrxAtomicLevels = [];
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
172 private $mTrxAutomaticAtomic = false;
174 * Track the write query callers of the current transaction
178 private $mTrxWriteCallers = [];
180 * @var float Seconds spent in write queries for the current transaction
182 private $mTrxWriteDuration = 0.0;
184 * @var integer Number of write queries for the current transaction
186 private $mTrxWriteQueryCount = 0;
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
190 private $mTrxWriteAdjDuration = 0.0;
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
194 private $mTrxWriteAdjQueryCount = 0;
196 * @var float RTT time estimate
198 private $mRTTEstimate = 0.0;
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
208 * @var resource File handle for upgrade
210 protected $fileHandle = null;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
239 * @param array $params Parameters passed from DatabaseBase::factory()
241 function __construct( array $params ) {
242 global $wgDBprefix, $wgDBmwschema;
244 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
246 $server = $params['host'];
247 $user = $params['user'];
248 $password = $params['password'];
249 $dbName = $params['dbname'];
250 $flags = $params['flags'];
251 $tablePrefix = $params['tablePrefix'];
252 $schema = $params['schema'];
253 $foreign = $params['foreign'];
255 $this->cliMode
= isset( $params['cliMode'] )
257 : ( PHP_SAPI
=== 'cli' );
259 $this->mFlags
= $flags;
260 if ( $this->mFlags
& DBO_DEFAULT
) {
261 if ( $this->cliMode
) {
262 $this->mFlags
&= ~DBO_TRX
;
264 $this->mFlags |
= DBO_TRX
;
268 $this->mSessionVars
= $params['variables'];
270 /** Get the default table prefix*/
271 if ( $tablePrefix === 'get from global' ) {
272 $this->mTablePrefix
= $wgDBprefix;
274 $this->mTablePrefix
= $tablePrefix;
277 /** Get the database schema*/
278 if ( $schema === 'get from global' ) {
279 $this->mSchema
= $wgDBmwschema;
281 $this->mSchema
= $schema;
284 $this->mForeign
= $foreign;
286 $this->profiler
= isset( $params['profiler'] )
287 ?
$params['profiler']
288 : Profiler
::instance(); // @TODO: remove global state
289 $this->trxProfiler
= isset( $params['trxProfiler'] )
290 ?
$params['trxProfiler']
291 : new TransactionProfiler();
292 $this->connLogger
= isset( $params['connLogger'] )
293 ?
$params['connLogger']
294 : new \Psr\Log\
NullLogger();
295 $this->queryLogger
= isset( $params['queryLogger'] )
296 ?
$params['queryLogger']
297 : new \Psr\Log\
NullLogger();
300 $this->open( $server, $user, $password, $dbName );
305 * Given a DB type, construct the name of the appropriate child class of
306 * IDatabase. This is designed to replace all of the manual stuff like:
307 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
308 * as well as validate against the canonical list of DB types we have
310 * This factory function is mostly useful for when you need to connect to a
311 * database other than the MediaWiki default (such as for external auth,
312 * an extension, et cetera). Do not use this to connect to the MediaWiki
313 * database. Example uses in core:
314 * @see LoadBalancer::reallyOpenConnection()
315 * @see ForeignDBRepo::getMasterDB()
316 * @see WebInstallerDBConnect::execute()
320 * @param string $dbType A possible DB type
321 * @param array $p An array of options to pass to the constructor.
322 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
323 * @return IDatabase|null If the database driver or extension cannot be found
324 * @throws InvalidArgumentException If the database driver or extension cannot be found
326 final public static function factory( $dbType, $p = [] ) {
327 global $wgCommandLineMode;
329 $canonicalDBTypes = [
330 'mysql' => [ 'mysqli', 'mysql' ],
338 $dbType = strtolower( $dbType );
339 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
340 $possibleDrivers = $canonicalDBTypes[$dbType];
341 if ( !empty( $p['driver'] ) ) {
342 if ( in_array( $p['driver'], $possibleDrivers ) ) {
343 $driver = $p['driver'];
345 throw new InvalidArgumentException( __METHOD__
.
346 " type '$dbType' does not support driver '{$p['driver']}'" );
349 foreach ( $possibleDrivers as $posDriver ) {
350 if ( extension_loaded( $posDriver ) ) {
351 $driver = $posDriver;
359 if ( $driver === false ) {
360 throw new InvalidArgumentException( __METHOD__
.
361 " no viable database extension found for type '$dbType'" );
364 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
365 // and everything else doesn't use a schema (e.g. null)
366 // Although postgres and oracle support schemas, we don't use them (yet)
367 // to maintain backwards compatibility
369 'mssql' => 'get from global',
372 $class = 'Database' . ucfirst( $driver );
373 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
374 // Resolve some defaults for b/c
375 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
376 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
377 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
378 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
379 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
380 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
381 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
382 if ( !isset( $p['schema'] ) ) {
383 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
385 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
386 $p['cliMode'] = $wgCommandLineMode;
388 $conn = new $class( $p );
389 if ( isset( $p['connLogger'] ) ) {
390 $conn->connLogger
= $p['connLogger'];
392 if ( isset( $p['queryLogger'] ) ) {
393 $conn->queryLogger
= $p['queryLogger'];
395 if ( isset( $p['errorLogger'] ) ) {
396 $conn->errorLogger
= $p['errorLogger'];
398 $conn->errorLogger
= [ MWExceptionHandler
::class, 'logException' ];
407 public function setLogger( LoggerInterface
$logger ) {
408 $this->queryLogger
= $logger;
411 public function getServerInfo() {
412 return $this->getServerVersion();
416 * @return string Command delimiter used by this database engine
418 public function getDelimiter() {
419 return $this->delimiter
;
423 * Boolean, controls output of large amounts of debug information.
424 * @param bool|null $debug
425 * - true to enable debugging
426 * - false to disable debugging
427 * - omitted or null to do nothing
429 * @return bool|null Previous value of the flag
431 public function debug( $debug = null ) {
432 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
435 public function bufferResults( $buffer = null ) {
436 if ( is_null( $buffer ) ) {
437 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
439 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
444 * Turns on (false) or off (true) the automatic generation and sending
445 * of a "we're sorry, but there has been a database error" page on
446 * database errors. Default is on (false). When turned off, the
447 * code should use lastErrno() and lastError() to handle the
448 * situation as appropriate.
450 * Do not use this function outside of the Database classes.
452 * @param null|bool $ignoreErrors
453 * @return bool The previous value of the flag.
455 protected function ignoreErrors( $ignoreErrors = null ) {
456 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
459 public function trxLevel() {
460 return $this->mTrxLevel
;
463 public function trxTimestamp() {
464 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
467 public function tablePrefix( $prefix = null ) {
468 return wfSetVar( $this->mTablePrefix
, $prefix );
471 public function dbSchema( $schema = null ) {
472 return wfSetVar( $this->mSchema
, $schema );
476 * Set the filehandle to copy write statements to.
478 * @param resource $fh File handle
480 public function setFileHandle( $fh ) {
481 $this->fileHandle
= $fh;
484 public function getLBInfo( $name = null ) {
485 if ( is_null( $name ) ) {
486 return $this->mLBInfo
;
488 if ( array_key_exists( $name, $this->mLBInfo
) ) {
489 return $this->mLBInfo
[$name];
496 public function setLBInfo( $name, $value = null ) {
497 if ( is_null( $value ) ) {
498 $this->mLBInfo
= $name;
500 $this->mLBInfo
[$name] = $value;
504 public function setLazyMasterHandle( IDatabase
$conn ) {
505 $this->lazyMasterHandle
= $conn;
509 * @return IDatabase|null
510 * @see setLazyMasterHandle()
513 public function getLazyMasterHandle() {
514 return $this->lazyMasterHandle
;
518 * @param TransactionProfiler $profiler
521 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
522 $this->trxProfiler
= $profiler;
526 * Returns true if this database supports (and uses) cascading deletes
530 public function cascadingDeletes() {
535 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
539 public function cleanupTriggers() {
544 * Returns true if this database is strict about what can be put into an IP field.
545 * Specifically, it uses a NULL value instead of an empty string.
549 public function strictIPs() {
554 * Returns true if this database uses timestamps rather than integers
558 public function realTimestamps() {
562 public function implicitGroupby() {
566 public function implicitOrderby() {
571 * Returns true if this database can do a native search on IP columns
572 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
576 public function searchableIPs() {
581 * Returns true if this database can use functional indexes
585 public function functionalIndexes() {
589 public function lastQuery() {
590 return $this->mLastQuery
;
593 public function doneWrites() {
594 return (bool)$this->mDoneWrites
;
597 public function lastDoneWrites() {
598 return $this->mDoneWrites ?
: false;
601 public function writesPending() {
602 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
605 public function writesOrCallbacksPending() {
606 return $this->mTrxLevel
&& (
607 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
611 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
612 if ( !$this->mTrxLevel
) {
614 } elseif ( !$this->mTrxDoneWrites
) {
619 case self
::ESTIMATE_DB_APPLY
:
621 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
622 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
623 // For omitted queries, make them count as something at least
624 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
625 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
628 default: // everything
629 return $this->mTrxWriteDuration
;
633 public function pendingWriteCallers() {
634 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
637 public function isOpen() {
638 return $this->mOpened
;
641 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
642 if ( $remember === self
::REMEMBER_PRIOR
) {
643 array_push( $this->priorFlags
, $this->mFlags
);
645 $this->mFlags |
= $flag;
648 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
649 if ( $remember === self
::REMEMBER_PRIOR
) {
650 array_push( $this->priorFlags
, $this->mFlags
);
652 $this->mFlags
&= ~
$flag;
655 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
656 if ( !$this->priorFlags
) {
660 if ( $state === self
::RESTORE_INITIAL
) {
661 $this->mFlags
= reset( $this->priorFlags
);
662 $this->priorFlags
= [];
664 $this->mFlags
= array_pop( $this->priorFlags
);
668 public function getFlag( $flag ) {
669 return !!( $this->mFlags
& $flag );
672 public function getProperty( $name ) {
676 public function getWikiID() {
677 if ( $this->mTablePrefix
) {
678 return "{$this->mDBname}-{$this->mTablePrefix}";
680 return $this->mDBname
;
685 * Get information about an index into an object
686 * @param string $table Table name
687 * @param string $index Index name
688 * @param string $fname Calling function name
689 * @return mixed Database-specific index description class or false if the index does not exist
691 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
694 * Wrapper for addslashes()
696 * @param string $s String to be slashed.
697 * @return string Slashed string.
699 abstract function strencode( $s );
702 * Called by serialize. Throw an exception when DB connection is serialized.
703 * This causes problems on some database engines because the connection is
704 * not restored on unserialize.
706 public function __sleep() {
707 throw new RuntimeException( 'Database serialization may cause problems, since ' .
708 'the connection is not restored on wakeup.' );
711 protected function installErrorHandler() {
712 $this->mPHPError
= false;
713 $this->htmlErrors
= ini_set( 'html_errors', '0' );
714 set_error_handler( [ $this, 'connectionerrorLogger' ] );
718 * @return bool|string
720 protected function restoreErrorHandler() {
721 restore_error_handler();
722 if ( $this->htmlErrors
!== false ) {
723 ini_set( 'html_errors', $this->htmlErrors
);
725 if ( $this->mPHPError
) {
726 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
727 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
737 * @param string $errstr
739 public function connectionerrorLogger( $errno, $errstr ) {
740 $this->mPHPError
= $errstr;
744 * Create a log context to pass to PSR logging functions.
746 * @param array $extras Additional data to add to context
749 protected function getLogContext( array $extras = [] ) {
752 'db_server' => $this->mServer
,
753 'db_name' => $this->mDBname
,
754 'db_user' => $this->mUser
,
760 public function close() {
761 if ( $this->mConn
) {
762 if ( $this->trxLevel() ) {
763 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
766 $closed = $this->closeConnection();
767 $this->mConn
= false;
768 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
769 throw new RuntimeException( "Transaction callbacks still pending." );
773 $this->mOpened
= false;
779 * Make sure isOpen() returns true as a sanity check
781 * @throws DBUnexpectedError
783 protected function assertOpen() {
784 if ( !$this->isOpen() ) {
785 throw new DBUnexpectedError( $this, "DB connection was already closed." );
790 * Closes underlying database connection
792 * @return bool Whether connection was closed successfully
794 abstract protected function closeConnection();
796 function reportConnectionError( $error = 'Unknown error' ) {
797 $myError = $this->lastError();
803 throw new DBConnectionError( $this, $error );
807 * The DBMS-dependent part of query()
809 * @param string $sql SQL query.
810 * @return ResultWrapper|bool Result object to feed to fetchObject,
811 * fetchRow, ...; or false on failure
813 abstract protected function doQuery( $sql );
816 * Determine whether a query writes to the DB.
817 * Should return true if unsure.
822 protected function isWriteQuery( $sql ) {
824 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
829 * @return string|null
831 protected function getQueryVerb( $sql ) {
832 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
836 * Determine whether a SQL statement is sensitive to isolation level.
837 * A SQL statement is considered transactable if its result could vary
838 * depending on the transaction isolation level. Operational commands
839 * such as 'SET' and 'SHOW' are not considered to be transactable.
844 protected function isTransactableQuery( $sql ) {
845 $verb = $this->getQueryVerb( $sql );
846 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
849 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
852 $priorWritesPending = $this->writesOrCallbacksPending();
853 $this->mLastQuery
= $sql;
855 $isWrite = $this->isWriteQuery( $sql );
857 $reason = $this->getReadOnlyReason();
858 if ( $reason !== false ) {
859 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
861 # Set a flag indicating that writes have been done
862 $this->mDoneWrites
= microtime( true );
865 # Add a comment for easy SHOW PROCESSLIST interpretation
866 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
867 $userName = $wgUser->getName();
868 if ( mb_strlen( $userName ) > 15 ) {
869 $userName = mb_substr( $userName, 0, 15 ) . '...';
871 $userName = str_replace( '/', '', $userName );
876 // Add trace comment to the begin of the sql string, right after the operator.
877 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
878 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
880 # Start implicit transactions that wrap the request if DBO_TRX is enabled
881 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
882 && $this->isTransactableQuery( $sql )
884 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
885 $this->mTrxAutomatic
= true;
888 # Keep track of whether the transaction has write queries pending
889 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
890 $this->mTrxDoneWrites
= true;
891 $this->trxProfiler
->transactionWritingIn(
892 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
895 if ( $this->debug() ) {
896 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
899 # Avoid fatals if close() was called
902 # Send the query to the server
903 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
905 # Try reconnecting if the connection was lost
906 if ( false === $ret && $this->wasErrorReissuable() ) {
907 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
908 # Stash the last error values before anything might clear them
909 $lastError = $this->lastError();
910 $lastErrno = $this->lastErrno();
911 # Update state tracking to reflect transaction loss due to disconnection
912 $this->handleTransactionLoss();
913 if ( $this->reconnect() ) {
914 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
915 $this->connLogger
->warning( $msg );
916 $this->queryLogger
->warning(
917 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
919 if ( !$recoverable ) {
920 # Callers may catch the exception and continue to use the DB
921 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
923 # Should be safe to silently retry the query
924 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
927 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
928 $this->connLogger
->error( $msg );
932 if ( false === $ret ) {
933 # Deadlocks cause the entire transaction to abort, not just the statement.
934 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
935 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
936 if ( $this->wasDeadlock() ) {
937 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
938 $tempIgnore = false; // not recoverable
940 # Update state tracking to reflect transaction loss
941 $this->handleTransactionLoss();
944 $this->reportQueryError(
945 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
948 $res = $this->resultObject( $ret );
953 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
954 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
955 # generalizeSQL() will probably cut down the query to reasonable
956 # logging size most of the time. The substr is really just a sanity check.
958 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
960 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
963 # Include query transaction state
964 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
966 $startTime = microtime( true );
967 $this->profiler
->profileIn( $queryProf );
968 $ret = $this->doQuery( $commentedSql );
969 $this->profiler
->profileOut( $queryProf );
970 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
972 unset( $queryProfSection ); // profile out (if set)
974 if ( $ret !== false ) {
975 $this->lastPing
= $startTime;
976 if ( $isWrite && $this->mTrxLevel
) {
977 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
978 $this->mTrxWriteCallers
[] = $fname;
982 if ( $sql === self
::PING_QUERY
) {
983 $this->mRTTEstimate
= $queryRuntime;
986 $this->trxProfiler
->recordQueryCompletion(
987 $queryProf, $startTime, $isWrite, $this->affectedRows()
989 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
995 * Update the estimated run-time of a query, not counting large row lock times
997 * LoadBalancer can be set to rollback transactions that will create huge replication
998 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
999 * queries, like inserting a row can take a long time due to row locking. This method
1000 * uses some simple heuristics to discount those cases.
1002 * @param string $sql A SQL write query
1003 * @param float $runtime Total runtime, including RTT
1005 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1006 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1007 $indicativeOfReplicaRuntime = true;
1008 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1009 $verb = $this->getQueryVerb( $sql );
1010 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1011 if ( $verb === 'INSERT' ) {
1012 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1013 } elseif ( $verb === 'REPLACE' ) {
1014 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1018 $this->mTrxWriteDuration +
= $runtime;
1019 $this->mTrxWriteQueryCount +
= 1;
1020 if ( $indicativeOfReplicaRuntime ) {
1021 $this->mTrxWriteAdjDuration +
= $runtime;
1022 $this->mTrxWriteAdjQueryCount +
= 1;
1026 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1027 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1028 # Dropped connections also mean that named locks are automatically released.
1029 # Only allow error suppression in autocommit mode or when the lost transaction
1030 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1031 if ( $this->mNamedLocksHeld
) {
1032 return false; // possible critical section violation
1033 } elseif ( $sql === 'COMMIT' ) {
1034 return !$priorWritesPending; // nothing written anyway? (T127428)
1035 } elseif ( $sql === 'ROLLBACK' ) {
1036 return true; // transaction lost...which is also what was requested :)
1037 } elseif ( $this->explicitTrxActive() ) {
1038 return false; // don't drop atomocity
1039 } elseif ( $priorWritesPending ) {
1040 return false; // prior writes lost from implicit transaction
1046 private function handleTransactionLoss() {
1047 $this->mTrxLevel
= 0;
1048 $this->mTrxIdleCallbacks
= []; // bug 65263
1049 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1051 // Handle callbacks in mTrxEndCallbacks
1052 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1053 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1055 } catch ( Exception
$e ) {
1056 // Already logged; move on...
1061 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1062 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1063 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1065 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1066 $this->queryLogger
->error(
1067 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1068 $this->getLogContext( [
1069 'method' => __METHOD__
,
1072 'sql1line' => $sql1line,
1076 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1077 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1082 * Intended to be compatible with the PEAR::DB wrapper functions.
1083 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1085 * ? = scalar value, quoted as necessary
1086 * ! = raw SQL bit (a function for instance)
1087 * & = filename; reads the file and inserts as a blob
1088 * (we don't use this though...)
1090 * @param string $sql
1091 * @param string $func
1095 protected function prepare( $sql, $func = __METHOD__
) {
1096 /* MySQL doesn't support prepared statements (yet), so just
1097 * pack up the query for reference. We'll manually replace
1100 return [ 'query' => $sql, 'func' => $func ];
1104 * Free a prepared query, generated by prepare().
1105 * @param string $prepared
1107 protected function freePrepared( $prepared ) {
1108 /* No-op by default */
1112 * Execute a prepared query with the various arguments
1113 * @param string $prepared The prepared sql
1114 * @param mixed $args Either an array here, or put scalars as varargs
1116 * @return ResultWrapper
1118 public function execute( $prepared, $args = null ) {
1119 if ( !is_array( $args ) ) {
1121 $args = func_get_args();
1122 array_shift( $args );
1125 $sql = $this->fillPrepared( $prepared['query'], $args );
1127 return $this->query( $sql, $prepared['func'] );
1131 * For faking prepared SQL statements on DBs that don't support it directly.
1133 * @param string $preparedQuery A 'preparable' SQL statement
1134 * @param array $args Array of Arguments to fill it with
1135 * @return string Executable SQL
1137 public function fillPrepared( $preparedQuery, $args ) {
1139 $this->preparedArgs
=& $args;
1141 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1142 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1146 * preg_callback func for fillPrepared()
1147 * The arguments should be in $this->preparedArgs and must not be touched
1148 * while we're doing this.
1150 * @param array $matches
1151 * @throws DBUnexpectedError
1154 protected function fillPreparedArg( $matches ) {
1155 switch ( $matches[1] ) {
1164 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1166 switch ( $matches[1] ) {
1168 return $this->addQuotes( $arg );
1172 # return $this->addQuotes( file_get_contents( $arg ) );
1173 throw new DBUnexpectedError(
1175 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1178 throw new DBUnexpectedError(
1180 'Received invalid match. This should never happen!'
1185 public function freeResult( $res ) {
1188 public function selectField(
1189 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1191 if ( $var === '*' ) { // sanity
1192 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1195 if ( !is_array( $options ) ) {
1196 $options = [ $options ];
1199 $options['LIMIT'] = 1;
1201 $res = $this->select( $table, $var, $cond, $fname, $options );
1202 if ( $res === false ||
!$this->numRows( $res ) ) {
1206 $row = $this->fetchRow( $res );
1208 if ( $row !== false ) {
1209 return reset( $row );
1215 public function selectFieldValues(
1216 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1218 if ( $var === '*' ) { // sanity
1219 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1220 } elseif ( !is_string( $var ) ) { // sanity
1221 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1224 if ( !is_array( $options ) ) {
1225 $options = [ $options ];
1228 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1229 if ( $res === false ) {
1234 foreach ( $res as $row ) {
1235 $values[] = $row->$var;
1242 * Returns an optional USE INDEX clause to go after the table, and a
1243 * string to go at the end of the query.
1245 * @param array $options Associative array of options to be turned into
1246 * an SQL query, valid keys are listed in the function.
1248 * @see DatabaseBase::select()
1250 public function makeSelectOptions( $options ) {
1251 $preLimitTail = $postLimitTail = '';
1256 foreach ( $options as $key => $option ) {
1257 if ( is_numeric( $key ) ) {
1258 $noKeyOptions[$option] = true;
1262 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1264 $preLimitTail .= $this->makeOrderBy( $options );
1266 // if (isset($options['LIMIT'])) {
1267 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1268 // isset($options['OFFSET']) ? $options['OFFSET']
1272 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1273 $postLimitTail .= ' FOR UPDATE';
1276 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1277 $postLimitTail .= ' LOCK IN SHARE MODE';
1280 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1281 $startOpts .= 'DISTINCT';
1284 # Various MySQL extensions
1285 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1286 $startOpts .= ' /*! STRAIGHT_JOIN */';
1289 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1290 $startOpts .= ' HIGH_PRIORITY';
1293 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1294 $startOpts .= ' SQL_BIG_RESULT';
1297 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1298 $startOpts .= ' SQL_BUFFER_RESULT';
1301 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1302 $startOpts .= ' SQL_SMALL_RESULT';
1305 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1306 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1309 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1310 $startOpts .= ' SQL_CACHE';
1313 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1314 $startOpts .= ' SQL_NO_CACHE';
1317 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1318 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1322 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1323 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1328 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1332 * Returns an optional GROUP BY with an optional HAVING
1334 * @param array $options Associative array of options
1336 * @see DatabaseBase::select()
1339 public function makeGroupByWithHaving( $options ) {
1341 if ( isset( $options['GROUP BY'] ) ) {
1342 $gb = is_array( $options['GROUP BY'] )
1343 ?
implode( ',', $options['GROUP BY'] )
1344 : $options['GROUP BY'];
1345 $sql .= ' GROUP BY ' . $gb;
1347 if ( isset( $options['HAVING'] ) ) {
1348 $having = is_array( $options['HAVING'] )
1349 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1350 : $options['HAVING'];
1351 $sql .= ' HAVING ' . $having;
1358 * Returns an optional ORDER BY
1360 * @param array $options Associative array of options
1362 * @see DatabaseBase::select()
1365 public function makeOrderBy( $options ) {
1366 if ( isset( $options['ORDER BY'] ) ) {
1367 $ob = is_array( $options['ORDER BY'] )
1368 ?
implode( ',', $options['ORDER BY'] )
1369 : $options['ORDER BY'];
1371 return ' ORDER BY ' . $ob;
1377 // See IDatabase::select for the docs for this function
1378 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1379 $options = [], $join_conds = [] ) {
1380 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1382 return $this->query( $sql, $fname );
1385 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1386 $options = [], $join_conds = []
1388 if ( is_array( $vars ) ) {
1389 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1392 $options = (array)$options;
1393 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1394 ?
$options['USE INDEX']
1396 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1397 ?
$options['IGNORE INDEX']
1400 if ( is_array( $table ) ) {
1402 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1403 } elseif ( $table != '' ) {
1404 if ( $table[0] == ' ' ) {
1405 $from = ' FROM ' . $table;
1408 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1414 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1415 $this->makeSelectOptions( $options );
1417 if ( !empty( $conds ) ) {
1418 if ( is_array( $conds ) ) {
1419 $conds = $this->makeList( $conds, LIST_AND
);
1421 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1423 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1426 if ( isset( $options['LIMIT'] ) ) {
1427 $sql = $this->limitResult( $sql, $options['LIMIT'],
1428 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1430 $sql = "$sql $postLimitTail";
1432 if ( isset( $options['EXPLAIN'] ) ) {
1433 $sql = 'EXPLAIN ' . $sql;
1439 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1440 $options = [], $join_conds = []
1442 $options = (array)$options;
1443 $options['LIMIT'] = 1;
1444 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1446 if ( $res === false ) {
1450 if ( !$this->numRows( $res ) ) {
1454 $obj = $this->fetchObject( $res );
1459 public function estimateRowCount(
1460 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1463 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1466 $row = $this->fetchRow( $res );
1467 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1473 public function selectRowCount(
1474 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1477 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1478 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1481 $row = $this->fetchRow( $res );
1482 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1489 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1490 * It's only slightly flawed. Don't use for anything important.
1492 * @param string $sql A SQL Query
1496 protected static function generalizeSQL( $sql ) {
1497 # This does the same as the regexp below would do, but in such a way
1498 # as to avoid crashing php on some large strings.
1499 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1501 $sql = str_replace( "\\\\", '', $sql );
1502 $sql = str_replace( "\\'", '', $sql );
1503 $sql = str_replace( "\\\"", '', $sql );
1504 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1505 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1507 # All newlines, tabs, etc replaced by single space
1508 $sql = preg_replace( '/\s+/', ' ', $sql );
1511 # except the ones surrounded by characters, e.g. l10n
1512 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1513 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1518 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1519 $info = $this->fieldInfo( $table, $field );
1524 public function indexExists( $table, $index, $fname = __METHOD__
) {
1525 if ( !$this->tableExists( $table ) ) {
1529 $info = $this->indexInfo( $table, $index, $fname );
1530 if ( is_null( $info ) ) {
1533 return $info !== false;
1537 public function tableExists( $table, $fname = __METHOD__
) {
1538 $table = $this->tableName( $table );
1539 $old = $this->ignoreErrors( true );
1540 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1541 $this->ignoreErrors( $old );
1546 public function indexUnique( $table, $index ) {
1547 $indexInfo = $this->indexInfo( $table, $index );
1549 if ( !$indexInfo ) {
1553 return !$indexInfo[0]->Non_unique
;
1557 * Helper for DatabaseBase::insert().
1559 * @param array $options
1562 protected function makeInsertOptions( $options ) {
1563 return implode( ' ', $options );
1566 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1567 # No rows to insert, easy just return now
1568 if ( !count( $a ) ) {
1572 $table = $this->tableName( $table );
1574 if ( !is_array( $options ) ) {
1575 $options = [ $options ];
1579 if ( isset( $options['fileHandle'] ) ) {
1580 $fh = $options['fileHandle'];
1582 $options = $this->makeInsertOptions( $options );
1584 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1586 $keys = array_keys( $a[0] );
1589 $keys = array_keys( $a );
1592 $sql = 'INSERT ' . $options .
1593 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1597 foreach ( $a as $row ) {
1603 $sql .= '(' . $this->makeList( $row ) . ')';
1606 $sql .= '(' . $this->makeList( $a ) . ')';
1609 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1611 } elseif ( $fh !== null ) {
1615 return (bool)$this->query( $sql, $fname );
1619 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1621 * @param array $options
1624 protected function makeUpdateOptionsArray( $options ) {
1625 if ( !is_array( $options ) ) {
1626 $options = [ $options ];
1631 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1632 $opts[] = $this->lowPriorityOption();
1635 if ( in_array( 'IGNORE', $options ) ) {
1643 * Make UPDATE options for the DatabaseBase::update function
1645 * @param array $options The options passed to DatabaseBase::update
1648 protected function makeUpdateOptions( $options ) {
1649 $opts = $this->makeUpdateOptionsArray( $options );
1651 return implode( ' ', $opts );
1654 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1655 $table = $this->tableName( $table );
1656 $opts = $this->makeUpdateOptions( $options );
1657 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1659 if ( $conds !== [] && $conds !== '*' ) {
1660 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1663 return $this->query( $sql, $fname );
1666 public function makeList( $a, $mode = LIST_COMMA
) {
1667 if ( !is_array( $a ) ) {
1668 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1674 foreach ( $a as $field => $value ) {
1676 if ( $mode == LIST_AND
) {
1678 } elseif ( $mode == LIST_OR
) {
1687 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1688 $list .= "($value)";
1689 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1691 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1692 // Remove null from array to be handled separately if found
1693 $includeNull = false;
1694 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1695 $includeNull = true;
1696 unset( $value[$nullKey] );
1698 if ( count( $value ) == 0 && !$includeNull ) {
1699 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1700 } elseif ( count( $value ) == 0 ) {
1701 // only check if $field is null
1702 $list .= "$field IS NULL";
1704 // IN clause contains at least one valid element
1705 if ( $includeNull ) {
1706 // Group subconditions to ensure correct precedence
1709 if ( count( $value ) == 1 ) {
1710 // Special-case single values, as IN isn't terribly efficient
1711 // Don't necessarily assume the single key is 0; we don't
1712 // enforce linear numeric ordering on other arrays here.
1713 $value = array_values( $value )[0];
1714 $list .= $field . " = " . $this->addQuotes( $value );
1716 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1718 // if null present in array, append IS NULL
1719 if ( $includeNull ) {
1720 $list .= " OR $field IS NULL)";
1723 } elseif ( $value === null ) {
1724 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1725 $list .= "$field IS ";
1726 } elseif ( $mode == LIST_SET
) {
1727 $list .= "$field = ";
1731 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1732 $list .= "$field = ";
1734 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1741 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1744 foreach ( $data as $base => $sub ) {
1745 if ( count( $sub ) ) {
1746 $conds[] = $this->makeList(
1747 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1753 return $this->makeList( $conds, LIST_OR
);
1755 // Nothing to search for...
1761 * Return aggregated value alias
1763 * @param array $valuedata
1764 * @param string $valuename
1768 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1772 public function bitNot( $field ) {
1776 public function bitAnd( $fieldLeft, $fieldRight ) {
1777 return "($fieldLeft & $fieldRight)";
1780 public function bitOr( $fieldLeft, $fieldRight ) {
1781 return "($fieldLeft | $fieldRight)";
1784 public function buildConcat( $stringList ) {
1785 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1788 public function buildGroupConcatField(
1789 $delim, $table, $field, $conds = '', $join_conds = []
1791 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1793 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1797 * @param string $field Field or column to cast
1801 public function buildStringCast( $field ) {
1805 public function selectDB( $db ) {
1806 # Stub. Shouldn't cause serious problems if it's not overridden, but
1807 # if your database engine supports a concept similar to MySQL's
1808 # databases you may as well.
1809 $this->mDBname
= $db;
1814 public function getDBname() {
1815 return $this->mDBname
;
1818 public function getServer() {
1819 return $this->mServer
;
1823 * Format a table name ready for use in constructing an SQL query
1825 * This does two important things: it quotes the table names to clean them up,
1826 * and it adds a table prefix if only given a table name with no quotes.
1828 * All functions of this object which require a table name call this function
1829 * themselves. Pass the canonical name to such functions. This is only needed
1830 * when calling query() directly.
1832 * @note This function does not sanitize user input. It is not safe to use
1833 * this function to escape user input.
1834 * @param string $name Database table name
1835 * @param string $format One of:
1836 * quoted - Automatically pass the table name through addIdentifierQuotes()
1837 * so that it can be used in a query.
1838 * raw - Do not add identifier quotes to the table name
1839 * @return string Full database name
1841 public function tableName( $name, $format = 'quoted' ) {
1842 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1843 # Skip the entire process when we have a string quoted on both ends.
1844 # Note that we check the end so that we will still quote any use of
1845 # use of `database`.table. But won't break things if someone wants
1846 # to query a database table with a dot in the name.
1847 if ( $this->isQuotedIdentifier( $name ) ) {
1851 # Lets test for any bits of text that should never show up in a table
1852 # name. Basically anything like JOIN or ON which are actually part of
1853 # SQL queries, but may end up inside of the table value to combine
1854 # sql. Such as how the API is doing.
1855 # Note that we use a whitespace test rather than a \b test to avoid
1856 # any remote case where a word like on may be inside of a table name
1857 # surrounded by symbols which may be considered word breaks.
1858 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1862 # Split database and table into proper variables.
1863 # We reverse the explode so that database.table and table both output
1864 # the correct table.
1865 $dbDetails = explode( '.', $name, 3 );
1866 if ( count( $dbDetails ) == 3 ) {
1867 list( $database, $schema, $table ) = $dbDetails;
1868 # We don't want any prefix added in this case
1870 } elseif ( count( $dbDetails ) == 2 ) {
1871 list( $database, $table ) = $dbDetails;
1872 # We don't want any prefix added in this case
1873 # In dbs that support it, $database may actually be the schema
1874 # but that doesn't affect any of the functionality here
1878 list( $table ) = $dbDetails;
1879 if ( $wgSharedDB !== null # We have a shared database
1880 && $this->mForeign
== false # We're not working on a foreign database
1881 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1882 && in_array( $table, $wgSharedTables ) # A shared table is selected
1884 $database = $wgSharedDB;
1885 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1886 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1889 $schema = $this->mSchema
; # Default schema
1890 $prefix = $this->mTablePrefix
; # Default prefix
1894 # Quote $table and apply the prefix if not quoted.
1895 # $tableName might be empty if this is called from Database::replaceVars()
1896 $tableName = "{$prefix}{$table}";
1897 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1898 $tableName = $this->addIdentifierQuotes( $tableName );
1901 # Quote $schema and merge it with the table name if needed
1902 if ( strlen( $schema ) ) {
1903 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1904 $schema = $this->addIdentifierQuotes( $schema );
1906 $tableName = $schema . '.' . $tableName;
1909 # Quote $database and merge it with the table name if needed
1910 if ( $database !== null ) {
1911 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1912 $database = $this->addIdentifierQuotes( $database );
1914 $tableName = $database . '.' . $tableName;
1921 * Fetch a number of table names into an array
1922 * This is handy when you need to construct SQL for joins
1925 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1926 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1927 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1931 public function tableNames() {
1932 $inArray = func_get_args();
1935 foreach ( $inArray as $name ) {
1936 $retVal[$name] = $this->tableName( $name );
1943 * Fetch a number of table names into an zero-indexed numerical array
1944 * This is handy when you need to construct SQL for joins
1947 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1948 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1949 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1953 public function tableNamesN() {
1954 $inArray = func_get_args();
1957 foreach ( $inArray as $name ) {
1958 $retVal[] = $this->tableName( $name );
1965 * Get an aliased table name
1966 * e.g. tableName AS newTableName
1968 * @param string $name Table name, see tableName()
1969 * @param string|bool $alias Alias (optional)
1970 * @return string SQL name for aliased table. Will not alias a table to its own name
1972 public function tableNameWithAlias( $name, $alias = false ) {
1973 if ( !$alias ||
$alias == $name ) {
1974 return $this->tableName( $name );
1976 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1981 * Gets an array of aliased table names
1983 * @param array $tables [ [alias] => table ]
1984 * @return string[] See tableNameWithAlias()
1986 public function tableNamesWithAlias( $tables ) {
1988 foreach ( $tables as $alias => $table ) {
1989 if ( is_numeric( $alias ) ) {
1992 $retval[] = $this->tableNameWithAlias( $table, $alias );
1999 * Get an aliased field name
2000 * e.g. fieldName AS newFieldName
2002 * @param string $name Field name
2003 * @param string|bool $alias Alias (optional)
2004 * @return string SQL name for aliased field. Will not alias a field to its own name
2006 public function fieldNameWithAlias( $name, $alias = false ) {
2007 if ( !$alias ||
(string)$alias === (string)$name ) {
2010 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2015 * Gets an array of aliased field names
2017 * @param array $fields [ [alias] => field ]
2018 * @return string[] See fieldNameWithAlias()
2020 public function fieldNamesWithAlias( $fields ) {
2022 foreach ( $fields as $alias => $field ) {
2023 if ( is_numeric( $alias ) ) {
2026 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2033 * Get the aliased table name clause for a FROM clause
2034 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2036 * @param array $tables ( [alias] => table )
2037 * @param array $use_index Same as for select()
2038 * @param array $ignore_index Same as for select()
2039 * @param array $join_conds Same as for select()
2042 protected function tableNamesWithIndexClauseOrJOIN(
2043 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2047 $use_index = (array)$use_index;
2048 $ignore_index = (array)$ignore_index;
2049 $join_conds = (array)$join_conds;
2051 foreach ( $tables as $alias => $table ) {
2052 if ( !is_string( $alias ) ) {
2053 // No alias? Set it equal to the table name
2056 // Is there a JOIN clause for this table?
2057 if ( isset( $join_conds[$alias] ) ) {
2058 list( $joinType, $conds ) = $join_conds[$alias];
2059 $tableClause = $joinType;
2060 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2061 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2062 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2064 $tableClause .= ' ' . $use;
2067 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2068 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2069 if ( $ignore != '' ) {
2070 $tableClause .= ' ' . $ignore;
2073 $on = $this->makeList( (array)$conds, LIST_AND
);
2075 $tableClause .= ' ON (' . $on . ')';
2078 $retJOIN[] = $tableClause;
2079 } elseif ( isset( $use_index[$alias] ) ) {
2080 // Is there an INDEX clause for this table?
2081 $tableClause = $this->tableNameWithAlias( $table, $alias );
2082 $tableClause .= ' ' . $this->useIndexClause(
2083 implode( ',', (array)$use_index[$alias] )
2086 $ret[] = $tableClause;
2087 } elseif ( isset( $ignore_index[$alias] ) ) {
2088 // Is there an INDEX clause for this table?
2089 $tableClause = $this->tableNameWithAlias( $table, $alias );
2090 $tableClause .= ' ' . $this->ignoreIndexClause(
2091 implode( ',', (array)$ignore_index[$alias] )
2094 $ret[] = $tableClause;
2096 $tableClause = $this->tableNameWithAlias( $table, $alias );
2098 $ret[] = $tableClause;
2102 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2103 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2104 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2106 // Compile our final table clause
2107 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2111 * Get the name of an index in a given table.
2113 * @param string $index
2116 protected function indexName( $index ) {
2117 // Backwards-compatibility hack
2119 'ar_usertext_timestamp' => 'usertext_timestamp',
2120 'un_user_id' => 'user_id',
2121 'un_user_ip' => 'user_ip',
2124 if ( isset( $renamed[$index] ) ) {
2125 return $renamed[$index];
2131 public function addQuotes( $s ) {
2132 if ( $s instanceof Blob
) {
2135 if ( $s === null ) {
2138 # This will also quote numeric values. This should be harmless,
2139 # and protects against weird problems that occur when they really
2140 # _are_ strings such as article titles and string->number->string
2141 # conversion is not 1:1.
2142 return "'" . $this->strencode( $s ) . "'";
2147 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2148 * MySQL uses `backticks` while basically everything else uses double quotes.
2149 * Since MySQL is the odd one out here the double quotes are our generic
2150 * and we implement backticks in DatabaseMysql.
2155 public function addIdentifierQuotes( $s ) {
2156 return '"' . str_replace( '"', '""', $s ) . '"';
2160 * Returns if the given identifier looks quoted or not according to
2161 * the database convention for quoting identifiers .
2163 * @note Do not use this to determine if untrusted input is safe.
2164 * A malicious user can trick this function.
2165 * @param string $name
2168 public function isQuotedIdentifier( $name ) {
2169 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2176 protected function escapeLikeInternal( $s ) {
2177 return addcslashes( $s, '\%_' );
2180 public function buildLike() {
2181 $params = func_get_args();
2183 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2184 $params = $params[0];
2189 foreach ( $params as $value ) {
2190 if ( $value instanceof LikeMatch
) {
2191 $s .= $value->toString();
2193 $s .= $this->escapeLikeInternal( $value );
2197 return " LIKE {$this->addQuotes( $s )} ";
2200 public function anyChar() {
2201 return new LikeMatch( '_' );
2204 public function anyString() {
2205 return new LikeMatch( '%' );
2208 public function nextSequenceValue( $seqName ) {
2213 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2214 * is only needed because a) MySQL must be as efficient as possible due to
2215 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2216 * which index to pick. Anyway, other databases might have different
2217 * indexes on a given table. So don't bother overriding this unless you're
2219 * @param string $index
2222 public function useIndexClause( $index ) {
2227 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2228 * is only needed because a) MySQL must be as efficient as possible due to
2229 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2230 * which index to pick. Anyway, other databases might have different
2231 * indexes on a given table. So don't bother overriding this unless you're
2233 * @param string $index
2236 public function ignoreIndexClause( $index ) {
2240 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2241 $quotedTable = $this->tableName( $table );
2243 if ( count( $rows ) == 0 ) {
2248 if ( !is_array( reset( $rows ) ) ) {
2252 // @FXIME: this is not atomic, but a trx would break affectedRows()
2253 foreach ( $rows as $row ) {
2254 # Delete rows which collide
2255 if ( $uniqueIndexes ) {
2256 $sql = "DELETE FROM $quotedTable WHERE ";
2258 foreach ( $uniqueIndexes as $index ) {
2265 if ( is_array( $index ) ) {
2267 foreach ( $index as $col ) {
2273 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2276 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2280 $this->query( $sql, $fname );
2283 # Now insert the row
2284 $this->insert( $table, $row, $fname );
2289 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2292 * @param string $table Table name
2293 * @param array|string $rows Row(s) to insert
2294 * @param string $fname Caller function name
2296 * @return ResultWrapper
2298 protected function nativeReplace( $table, $rows, $fname ) {
2299 $table = $this->tableName( $table );
2302 if ( !is_array( reset( $rows ) ) ) {
2306 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2309 foreach ( $rows as $row ) {
2316 $sql .= '(' . $this->makeList( $row ) . ')';
2319 return $this->query( $sql, $fname );
2322 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2325 if ( !count( $rows ) ) {
2326 return true; // nothing to do
2329 if ( !is_array( reset( $rows ) ) ) {
2333 if ( count( $uniqueIndexes ) ) {
2334 $clauses = []; // list WHERE clauses that each identify a single row
2335 foreach ( $rows as $row ) {
2336 foreach ( $uniqueIndexes as $index ) {
2337 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2338 $rowKey = []; // unique key to this row
2339 foreach ( $index as $column ) {
2340 $rowKey[$column] = $row[$column];
2342 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2345 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2350 $useTrx = !$this->mTrxLevel
;
2352 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2355 # Update any existing conflicting row(s)
2356 if ( $where !== false ) {
2357 $ok = $this->update( $table, $set, $where, $fname );
2361 # Now insert any non-conflicting row(s)
2362 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2363 } catch ( Exception
$e ) {
2365 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2370 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2376 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2380 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2383 $delTable = $this->tableName( $delTable );
2384 $joinTable = $this->tableName( $joinTable );
2385 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2386 if ( $conds != '*' ) {
2387 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2391 $this->query( $sql, $fname );
2395 * Returns the size of a text field, or -1 for "unlimited"
2397 * @param string $table
2398 * @param string $field
2401 public function textFieldSize( $table, $field ) {
2402 $table = $this->tableName( $table );
2403 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2404 $res = $this->query( $sql, __METHOD__
);
2405 $row = $this->fetchObject( $res );
2409 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2419 * A string to insert into queries to show that they're low-priority, like
2420 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2421 * string and nothing bad should happen.
2423 * @return string Returns the text of the low priority option if it is
2424 * supported, or a blank string otherwise
2426 public function lowPriorityOption() {
2430 public function delete( $table, $conds, $fname = __METHOD__
) {
2432 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2435 $table = $this->tableName( $table );
2436 $sql = "DELETE FROM $table";
2438 if ( $conds != '*' ) {
2439 if ( is_array( $conds ) ) {
2440 $conds = $this->makeList( $conds, LIST_AND
);
2442 $sql .= ' WHERE ' . $conds;
2445 return $this->query( $sql, $fname );
2448 public function insertSelect(
2449 $destTable, $srcTable, $varMap, $conds,
2450 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2452 if ( $this->cliMode
) {
2453 // For massive migrations with downtime, we don't want to select everything
2454 // into memory and OOM, so do all this native on the server side if possible.
2455 return $this->nativeInsertSelect(
2466 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2467 // on only the master (without needing row-based-replication). It also makes it easy to
2468 // know how big the INSERT is going to be.
2470 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2471 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2473 $selectOptions[] = 'FOR UPDATE';
2474 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2480 foreach ( $res as $row ) {
2481 $rows[] = (array)$row;
2484 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2487 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2488 $fname = __METHOD__
,
2489 $insertOptions = [], $selectOptions = []
2491 $destTable = $this->tableName( $destTable );
2493 if ( !is_array( $insertOptions ) ) {
2494 $insertOptions = [ $insertOptions ];
2497 $insertOptions = $this->makeInsertOptions( $insertOptions );
2499 if ( !is_array( $selectOptions ) ) {
2500 $selectOptions = [ $selectOptions ];
2503 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2506 if ( is_array( $srcTable ) ) {
2507 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2509 $srcTable = $this->tableName( $srcTable );
2512 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2513 " SELECT $startOpts " . implode( ',', $varMap ) .
2514 " FROM $srcTable $useIndex $ignoreIndex ";
2516 if ( $conds != '*' ) {
2517 if ( is_array( $conds ) ) {
2518 $conds = $this->makeList( $conds, LIST_AND
);
2520 $sql .= " WHERE $conds";
2523 $sql .= " $tailOpts";
2525 return $this->query( $sql, $fname );
2529 * Construct a LIMIT query with optional offset. This is used for query
2530 * pages. The SQL should be adjusted so that only the first $limit rows
2531 * are returned. If $offset is provided as well, then the first $offset
2532 * rows should be discarded, and the next $limit rows should be returned.
2533 * If the result of the query is not ordered, then the rows to be returned
2534 * are theoretically arbitrary.
2536 * $sql is expected to be a SELECT, if that makes a difference.
2538 * The version provided by default works in MySQL and SQLite. It will very
2539 * likely need to be overridden for most other DBMSes.
2541 * @param string $sql SQL query we will append the limit too
2542 * @param int $limit The SQL limit
2543 * @param int|bool $offset The SQL offset (default false)
2544 * @throws DBUnexpectedError
2547 public function limitResult( $sql, $limit, $offset = false ) {
2548 if ( !is_numeric( $limit ) ) {
2549 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2552 return "$sql LIMIT "
2553 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2557 public function unionSupportsOrderAndLimit() {
2558 return true; // True for almost every DB supported
2561 public function unionQueries( $sqls, $all ) {
2562 $glue = $all ?
') UNION ALL (' : ') UNION (';
2564 return '(' . implode( $glue, $sqls ) . ')';
2567 public function conditional( $cond, $trueVal, $falseVal ) {
2568 if ( is_array( $cond ) ) {
2569 $cond = $this->makeList( $cond, LIST_AND
);
2572 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2575 public function strreplace( $orig, $old, $new ) {
2576 return "REPLACE({$orig}, {$old}, {$new})";
2579 public function getServerUptime() {
2583 public function wasDeadlock() {
2587 public function wasLockTimeout() {
2591 public function wasErrorReissuable() {
2595 public function wasReadOnlyError() {
2600 * Determines if the given query error was a connection drop
2603 * @param integer|string $errno
2606 public function wasConnectionError( $errno ) {
2611 * Perform a deadlock-prone transaction.
2613 * This function invokes a callback function to perform a set of write
2614 * queries. If a deadlock occurs during the processing, the transaction
2615 * will be rolled back and the callback function will be called again.
2617 * Avoid using this method outside of Job or Maintenance classes.
2620 * $dbw->deadlockLoop( callback, ... );
2622 * Extra arguments are passed through to the specified callback function.
2623 * This method requires that no transactions are already active to avoid
2624 * causing premature commits or exceptions.
2626 * Returns whatever the callback function returned on its successful,
2627 * iteration, or false on error, for example if the retry limit was
2631 * @throws DBUnexpectedError
2634 public function deadlockLoop() {
2635 $args = func_get_args();
2636 $function = array_shift( $args );
2637 $tries = self
::DEADLOCK_TRIES
;
2639 $this->begin( __METHOD__
);
2642 /** @var Exception $e */
2646 $retVal = call_user_func_array( $function, $args );
2648 } catch ( DBQueryError
$e ) {
2649 if ( $this->wasDeadlock() ) {
2650 // Retry after a randomized delay
2651 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2653 // Throw the error back up
2657 } while ( --$tries > 0 );
2659 if ( $tries <= 0 ) {
2660 // Too many deadlocks; give up
2661 $this->rollback( __METHOD__
);
2664 $this->commit( __METHOD__
);
2670 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2671 # Real waits are implemented in the subclass.
2675 public function getSlavePos() {
2680 public function getMasterPos() {
2685 public function serverIsReadOnly() {
2689 final public function onTransactionResolution( callable
$callback ) {
2690 if ( !$this->mTrxLevel
) {
2691 throw new DBUnexpectedError( $this, "No transaction is active." );
2693 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2696 final public function onTransactionIdle( callable
$callback ) {
2697 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2698 if ( !$this->mTrxLevel
) {
2699 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2703 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2704 if ( $this->mTrxLevel
) {
2705 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2707 // If no transaction is active, then make one for this callback
2708 $this->startAtomic( __METHOD__
);
2710 call_user_func( $callback );
2711 $this->endAtomic( __METHOD__
);
2712 } catch ( Exception
$e ) {
2713 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2719 final public function setTransactionListener( $name, callable
$callback = null ) {
2721 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2723 unset( $this->mTrxRecurringCallbacks
[$name] );
2728 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2730 * This method should not be used outside of Database/LoadBalancer
2732 * @param bool $suppress
2735 final public function setTrxEndCallbackSuppression( $suppress ) {
2736 $this->mTrxEndCallbacksSuppressed
= $suppress;
2740 * Actually run and consume any "on transaction idle/resolution" callbacks.
2742 * This method should not be used outside of Database/LoadBalancer
2744 * @param integer $trigger IDatabase::TRIGGER_* constant
2748 public function runOnTransactionIdleCallbacks( $trigger ) {
2749 if ( $this->mTrxEndCallbacksSuppressed
) {
2753 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2754 /** @var Exception $e */
2755 $e = null; // first exception
2756 do { // callbacks may add callbacks :)
2757 $callbacks = array_merge(
2758 $this->mTrxIdleCallbacks
,
2759 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2761 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2762 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2763 foreach ( $callbacks as $callback ) {
2765 list( $phpCallback ) = $callback;
2766 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2767 call_user_func_array( $phpCallback, [ $trigger ] );
2769 $this->setFlag( DBO_TRX
); // restore automatic begin()
2771 $this->clearFlag( DBO_TRX
); // restore auto-commit
2773 } catch ( Exception
$ex ) {
2774 call_user_func( $this->errorLogger
, $ex );
2776 // Some callbacks may use startAtomic/endAtomic, so make sure
2777 // their transactions are ended so other callbacks don't fail
2778 if ( $this->trxLevel() ) {
2779 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2783 } while ( count( $this->mTrxIdleCallbacks
) );
2785 if ( $e instanceof Exception
) {
2786 throw $e; // re-throw any first exception
2791 * Actually run and consume any "on transaction pre-commit" callbacks.
2793 * This method should not be used outside of Database/LoadBalancer
2798 public function runOnTransactionPreCommitCallbacks() {
2799 $e = null; // first exception
2800 do { // callbacks may add callbacks :)
2801 $callbacks = $this->mTrxPreCommitCallbacks
;
2802 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2803 foreach ( $callbacks as $callback ) {
2805 list( $phpCallback ) = $callback;
2806 call_user_func( $phpCallback );
2807 } catch ( Exception
$ex ) {
2808 call_user_func( $this->errorLogger
, $ex );
2812 } while ( count( $this->mTrxPreCommitCallbacks
) );
2814 if ( $e instanceof Exception
) {
2815 throw $e; // re-throw any first exception
2820 * Actually run any "transaction listener" callbacks.
2822 * This method should not be used outside of Database/LoadBalancer
2824 * @param integer $trigger IDatabase::TRIGGER_* constant
2828 public function runTransactionListenerCallbacks( $trigger ) {
2829 if ( $this->mTrxEndCallbacksSuppressed
) {
2833 /** @var Exception $e */
2834 $e = null; // first exception
2836 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2838 list( $phpCallback ) = $callback;
2839 $phpCallback( $trigger, $this );
2840 } catch ( Exception
$ex ) {
2841 call_user_func( $this->errorLogger
, $ex );
2846 if ( $e instanceof Exception
) {
2847 throw $e; // re-throw any first exception
2851 final public function startAtomic( $fname = __METHOD__
) {
2852 if ( !$this->mTrxLevel
) {
2853 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2854 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2855 // in all changes being in one transaction to keep requests transactional.
2856 if ( !$this->getFlag( DBO_TRX
) ) {
2857 $this->mTrxAutomaticAtomic
= true;
2861 $this->mTrxAtomicLevels
[] = $fname;
2864 final public function endAtomic( $fname = __METHOD__
) {
2865 if ( !$this->mTrxLevel
) {
2866 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2868 if ( !$this->mTrxAtomicLevels ||
2869 array_pop( $this->mTrxAtomicLevels
) !== $fname
2871 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2874 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2875 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2879 final public function doAtomicSection( $fname, callable
$callback ) {
2880 $this->startAtomic( $fname );
2882 $res = call_user_func_array( $callback, [ $this, $fname ] );
2883 } catch ( Exception
$e ) {
2884 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2887 $this->endAtomic( $fname );
2892 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2893 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2894 if ( $this->mTrxLevel
) {
2895 if ( $this->mTrxAtomicLevels
) {
2896 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2897 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2898 throw new DBUnexpectedError( $this, $msg );
2899 } elseif ( !$this->mTrxAutomatic
) {
2900 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2901 throw new DBUnexpectedError( $this, $msg );
2903 // @TODO: make this an exception at some point
2904 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2905 $this->queryLogger
->error( $msg );
2906 return; // join the main transaction set
2908 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2909 // @TODO: make this an exception at some point
2910 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2911 $this->queryLogger
->error( $msg );
2912 return; // let any writes be in the main transaction
2915 // Avoid fatals if close() was called
2916 $this->assertOpen();
2918 $this->doBegin( $fname );
2919 $this->mTrxTimestamp
= microtime( true );
2920 $this->mTrxFname
= $fname;
2921 $this->mTrxDoneWrites
= false;
2922 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2923 $this->mTrxAutomaticAtomic
= false;
2924 $this->mTrxAtomicLevels
= [];
2925 $this->mTrxShortId
= wfRandomString( 12 );
2926 $this->mTrxWriteDuration
= 0.0;
2927 $this->mTrxWriteQueryCount
= 0;
2928 $this->mTrxWriteAdjDuration
= 0.0;
2929 $this->mTrxWriteAdjQueryCount
= 0;
2930 $this->mTrxWriteCallers
= [];
2931 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2932 // Get an estimate of the replica DB lag before then, treating estimate staleness
2933 // as lag itself just to be safe
2934 $status = $this->getApproximateLagStatus();
2935 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2939 * Issues the BEGIN command to the database server.
2941 * @see DatabaseBase::begin()
2942 * @param string $fname
2944 protected function doBegin( $fname ) {
2945 $this->query( 'BEGIN', $fname );
2946 $this->mTrxLevel
= 1;
2949 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2950 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2951 // There are still atomic sections open. This cannot be ignored
2952 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2953 throw new DBUnexpectedError(
2955 "$fname: Got COMMIT while atomic sections $levels are still open."
2959 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2960 if ( !$this->mTrxLevel
) {
2961 return; // nothing to do
2962 } elseif ( !$this->mTrxAutomatic
) {
2963 throw new DBUnexpectedError(
2965 "$fname: Flushing an explicit transaction, getting out of sync."
2969 if ( !$this->mTrxLevel
) {
2970 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2971 return; // nothing to do
2972 } elseif ( $this->mTrxAutomatic
) {
2973 // @TODO: make this an exception at some point
2974 $msg = "$fname: Explicit commit of implicit transaction.";
2975 $this->queryLogger
->error( $msg );
2976 return; // wait for the main transaction set commit round
2980 // Avoid fatals if close() was called
2981 $this->assertOpen();
2983 $this->runOnTransactionPreCommitCallbacks();
2984 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2985 $this->doCommit( $fname );
2986 if ( $this->mTrxDoneWrites
) {
2987 $this->mDoneWrites
= microtime( true );
2988 $this->trxProfiler
->transactionWritingOut(
2989 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2992 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2993 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2997 * Issues the COMMIT command to the database server.
2999 * @see DatabaseBase::commit()
3000 * @param string $fname
3002 protected function doCommit( $fname ) {
3003 if ( $this->mTrxLevel
) {
3004 $this->query( 'COMMIT', $fname );
3005 $this->mTrxLevel
= 0;
3009 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3010 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3011 if ( !$this->mTrxLevel
) {
3012 return; // nothing to do
3015 if ( !$this->mTrxLevel
) {
3016 $this->queryLogger
->error(
3017 "$fname: No transaction to rollback, something got out of sync." );
3018 return; // nothing to do
3019 } elseif ( $this->getFlag( DBO_TRX
) ) {
3020 throw new DBUnexpectedError(
3022 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3027 // Avoid fatals if close() was called
3028 $this->assertOpen();
3030 $this->doRollback( $fname );
3031 $this->mTrxAtomicLevels
= [];
3032 if ( $this->mTrxDoneWrites
) {
3033 $this->trxProfiler
->transactionWritingOut(
3034 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3037 $this->mTrxIdleCallbacks
= []; // clear
3038 $this->mTrxPreCommitCallbacks
= []; // clear
3039 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3040 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3044 * Issues the ROLLBACK command to the database server.
3046 * @see DatabaseBase::rollback()
3047 * @param string $fname
3049 protected function doRollback( $fname ) {
3050 if ( $this->mTrxLevel
) {
3051 # Disconnects cause rollback anyway, so ignore those errors
3052 $ignoreErrors = true;
3053 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3054 $this->mTrxLevel
= 0;
3058 public function flushSnapshot( $fname = __METHOD__
) {
3059 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3060 // This only flushes transactions to clear snapshots, not to write data
3061 throw new DBUnexpectedError(
3063 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3067 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3070 public function explicitTrxActive() {
3071 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3075 * Creates a new table with structure copied from existing table
3076 * Note that unlike most database abstraction functions, this function does not
3077 * automatically append database prefix, because it works at a lower
3078 * abstraction level.
3079 * The table names passed to this function shall not be quoted (this
3080 * function calls addIdentifierQuotes when needed).
3082 * @param string $oldName Name of table whose structure should be copied
3083 * @param string $newName Name of table to be created
3084 * @param bool $temporary Whether the new table should be temporary
3085 * @param string $fname Calling function name
3086 * @throws RuntimeException
3087 * @return bool True if operation was successful
3089 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3092 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3095 function listTables( $prefix = null, $fname = __METHOD__
) {
3096 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3100 * Reset the views process cache set by listViews()
3103 final public function clearViewsCache() {
3104 $this->allViews
= null;
3108 * Lists all the VIEWs in the database
3110 * For caching purposes the list of all views should be stored in
3111 * $this->allViews. The process cache can be cleared with clearViewsCache()
3113 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3114 * @param string $fname Name of calling function
3115 * @throws RuntimeException
3119 public function listViews( $prefix = null, $fname = __METHOD__
) {
3120 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3124 * Differentiates between a TABLE and a VIEW
3126 * @param string $name Name of the database-structure to test.
3127 * @throws RuntimeException
3131 public function isView( $name ) {
3132 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3135 public function timestamp( $ts = 0 ) {
3136 return wfTimestamp( TS_MW
, $ts );
3139 public function timestampOrNull( $ts = null ) {
3140 if ( is_null( $ts ) ) {
3143 return $this->timestamp( $ts );
3148 * Take the result from a query, and wrap it in a ResultWrapper if
3149 * necessary. Boolean values are passed through as is, to indicate success
3150 * of write queries or failure.
3152 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3153 * resource, and it was necessary to call this function to convert it to
3154 * a wrapper. Nowadays, raw database objects are never exposed to external
3155 * callers, so this is unnecessary in external code.
3157 * @param bool|ResultWrapper|resource|object $result
3158 * @return bool|ResultWrapper
3160 protected function resultObject( $result ) {
3163 } elseif ( $result instanceof ResultWrapper
) {
3165 } elseif ( $result === true ) {
3166 // Successful write query
3169 return new ResultWrapper( $this, $result );
3173 public function ping( &$rtt = null ) {
3174 // Avoid hitting the server if it was hit recently
3175 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3176 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3177 $rtt = $this->mRTTEstimate
;
3178 return true; // don't care about $rtt
3182 // This will reconnect if possible or return false if not
3183 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3184 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3185 $this->restoreFlags( self
::RESTORE_PRIOR
);
3188 $rtt = $this->mRTTEstimate
;
3197 protected function reconnect() {
3198 $this->closeConnection();
3199 $this->mOpened
= false;
3200 $this->mConn
= false;
3202 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3203 $this->lastPing
= microtime( true );
3205 } catch ( DBConnectionError
$e ) {
3212 public function getSessionLagStatus() {
3213 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3217 * Get the replica DB lag when the current transaction started
3219 * This is useful when transactions might use snapshot isolation
3220 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3221 * is this lag plus transaction duration. If they don't, it is still
3222 * safe to be pessimistic. This returns null if there is no transaction.
3224 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3227 public function getTransactionLagStatus() {
3228 return $this->mTrxLevel
3229 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3234 * Get a replica DB lag estimate for this server
3236 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3239 public function getApproximateLagStatus() {
3241 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3242 'since' => microtime( true )
3247 * Merge the result of getSessionLagStatus() for several DBs
3248 * using the most pessimistic values to estimate the lag of
3249 * any data derived from them in combination
3251 * This is information is useful for caching modules
3253 * @see WANObjectCache::set()
3254 * @see WANObjectCache::getWithSetCallback()
3256 * @param IDatabase $db1
3257 * @param IDatabase ...
3258 * @return array Map of values:
3259 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3260 * - since: oldest UNIX timestamp of any of the DB lag estimates
3261 * - pending: whether any of the DBs have uncommitted changes
3264 public static function getCacheSetOptions( IDatabase
$db1 ) {
3265 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3266 foreach ( func_get_args() as $db ) {
3267 /** @var IDatabase $db */
3268 $status = $db->getSessionLagStatus();
3269 if ( $status['lag'] === false ) {
3270 $res['lag'] = false;
3271 } elseif ( $res['lag'] !== false ) {
3272 $res['lag'] = max( $res['lag'], $status['lag'] );
3274 $res['since'] = min( $res['since'], $status['since'] );
3275 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3281 public function getLag() {
3285 function maxListLen() {
3289 public function encodeBlob( $b ) {
3293 public function decodeBlob( $b ) {
3294 if ( $b instanceof Blob
) {
3300 public function setSessionOptions( array $options ) {
3304 * Read and execute SQL commands from a file.
3306 * Returns true on success, error string or exception on failure (depending
3307 * on object's error ignore settings).
3309 * @param string $filename File name to open
3310 * @param bool|callable $lineCallback Optional function called before reading each line
3311 * @param bool|callable $resultCallback Optional function called for each MySQL result
3312 * @param bool|string $fname Calling function name or false if name should be
3313 * generated dynamically using $filename
3314 * @param bool|callable $inputCallback Optional function called for each
3315 * complete line sent
3316 * @return bool|string
3319 public function sourceFile(
3320 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3322 MediaWiki\
suppressWarnings();
3323 $fp = fopen( $filename, 'r' );
3324 MediaWiki\restoreWarnings
();
3326 if ( false === $fp ) {
3327 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3331 $fname = __METHOD__
. "( $filename )";
3335 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3336 } catch ( Exception
$e ) {
3346 public function setSchemaVars( $vars ) {
3347 $this->mSchemaVars
= $vars;
3351 * Read and execute commands from an open file handle.
3353 * Returns true on success, error string or exception on failure (depending
3354 * on object's error ignore settings).
3356 * @param resource $fp File handle
3357 * @param bool|callable $lineCallback Optional function called before reading each query
3358 * @param bool|callable $resultCallback Optional function called for each MySQL result
3359 * @param string $fname Calling function name
3360 * @param bool|callable $inputCallback Optional function called for each complete query sent
3361 * @return bool|string
3363 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3364 $fname = __METHOD__
, $inputCallback = false
3368 while ( !feof( $fp ) ) {
3369 if ( $lineCallback ) {
3370 call_user_func( $lineCallback );
3373 $line = trim( fgets( $fp ) );
3375 if ( $line == '' ) {
3379 if ( '-' == $line[0] && '-' == $line[1] ) {
3387 $done = $this->streamStatementEnd( $cmd, $line );
3391 if ( $done ||
feof( $fp ) ) {
3392 $cmd = $this->replaceVars( $cmd );
3394 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3395 $res = $this->query( $cmd, $fname );
3397 if ( $resultCallback ) {
3398 call_user_func( $resultCallback, $res, $this );
3401 if ( false === $res ) {
3402 $err = $this->lastError();
3404 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3415 * Called by sourceStream() to check if we've reached a statement end
3417 * @param string $sql SQL assembled so far
3418 * @param string $newLine New line about to be added to $sql
3419 * @return bool Whether $newLine contains end of the statement
3421 public function streamStatementEnd( &$sql, &$newLine ) {
3422 if ( $this->delimiter
) {
3424 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3425 if ( $newLine != $prev ) {
3434 * Database independent variable replacement. Replaces a set of variables
3435 * in an SQL statement with their contents as given by $this->getSchemaVars().
3437 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3439 * - '{$var}' should be used for text and is passed through the database's
3441 * - `{$var}` should be used for identifiers (e.g. table and database names).
3442 * It is passed through the database's addIdentifierQuotes method which
3443 * can be overridden if the database uses something other than backticks.
3444 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3445 * database's tableName method.
3446 * - / *i* / passes the name that follows through the database's indexName method.
3447 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3448 * its use should be avoided. In 1.24 and older, string encoding was applied.
3450 * @param string $ins SQL statement to replace variables in
3451 * @return string The new SQL statement with variables replaced
3453 protected function replaceVars( $ins ) {
3454 $vars = $this->getSchemaVars();
3455 return preg_replace_callback(
3457 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3458 \'\{\$ (\w+) }\' | # 3. addQuotes
3459 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3460 /\*\$ (\w+) \*/ # 5. leave unencoded
3462 function ( $m ) use ( $vars ) {
3463 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3464 // check for both nonexistent keys *and* the empty string.
3465 if ( isset( $m[1] ) && $m[1] !== '' ) {
3466 if ( $m[1] === 'i' ) {
3467 return $this->indexName( $m[2] );
3469 return $this->tableName( $m[2] );
3471 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3472 return $this->addQuotes( $vars[$m[3]] );
3473 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3474 return $this->addIdentifierQuotes( $vars[$m[4]] );
3475 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3476 return $vars[$m[5]];
3486 * Get schema variables. If none have been set via setSchemaVars(), then
3487 * use some defaults from the current object.
3491 protected function getSchemaVars() {
3492 if ( $this->mSchemaVars
) {
3493 return $this->mSchemaVars
;
3495 return $this->getDefaultSchemaVars();
3500 * Get schema variables to use if none have been set via setSchemaVars().
3502 * Override this in derived classes to provide variables for tables.sql
3503 * and SQL patch files.
3507 protected function getDefaultSchemaVars() {
3511 public function lockIsFree( $lockName, $method ) {
3515 public function lock( $lockName, $method, $timeout = 5 ) {
3516 $this->mNamedLocksHeld
[$lockName] = 1;
3521 public function unlock( $lockName, $method ) {
3522 unset( $this->mNamedLocksHeld
[$lockName] );
3527 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3528 if ( $this->writesOrCallbacksPending() ) {
3529 // This only flushes transactions to clear snapshots, not to write data
3530 throw new DBUnexpectedError(
3532 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3536 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3540 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3541 if ( $this->trxLevel() ) {
3542 // There is a good chance an exception was thrown, causing any early return
3543 // from the caller. Let any error handler get a chance to issue rollback().
3544 // If there isn't one, let the error bubble up and trigger server-side rollback.
3545 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3546 $this->unlock( $lockKey, $fname );
3549 $this->unlock( $lockKey, $fname );
3553 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3558 public function namedLocksEnqueue() {
3563 * Lock specific tables
3565 * @param array $read Array of tables to lock for read access
3566 * @param array $write Array of tables to lock for write access
3567 * @param string $method Name of caller
3568 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3571 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3576 * Unlock specific tables
3578 * @param string $method The caller
3581 public function unlockTables( $method ) {
3587 * @param string $tableName
3588 * @param string $fName
3589 * @return bool|ResultWrapper
3592 public function dropTable( $tableName, $fName = __METHOD__
) {
3593 if ( !$this->tableExists( $tableName, $fName ) ) {
3596 $sql = "DROP TABLE " . $this->tableName( $tableName );
3597 if ( $this->cascadingDeletes() ) {
3601 return $this->query( $sql, $fName );
3605 * Get search engine class. All subclasses of this need to implement this
3606 * if they wish to use searching.
3610 public function getSearchEngine() {
3611 return 'SearchEngineDummy';
3614 public function getInfinity() {
3618 public function encodeExpiry( $expiry ) {
3619 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3620 ?
$this->getInfinity()
3621 : $this->timestamp( $expiry );
3624 public function decodeExpiry( $expiry, $format = TS_MW
) {
3625 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3627 : wfTimestamp( $format, $expiry );
3630 public function setBigSelects( $value = true ) {
3634 public function isReadOnly() {
3635 return ( $this->getReadOnlyReason() !== false );
3639 * @return string|bool Reason this DB is read-only or false if it is not
3641 protected function getReadOnlyReason() {
3642 $reason = $this->getLBInfo( 'readOnlyReason' );
3644 return is_string( $reason ) ?
$reason : false;
3651 public function __toString() {
3652 return (string)$this->mConn
;
3656 * Run a few simple sanity checks
3658 public function __destruct() {
3659 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3660 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3662 $danglingCallbacks = array_merge(
3663 $this->mTrxIdleCallbacks
,
3664 $this->mTrxPreCommitCallbacks
,
3665 $this->mTrxEndCallbacks
3667 if ( $danglingCallbacks ) {
3669 foreach ( $danglingCallbacks as $callbackInfo ) {
3670 $callers[] = $callbackInfo[1];
3672 $callers = implode( ', ', $callers );
3673 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3681 abstract class Database
extends DatabaseBase
{
3682 // B/C until nothing type hints for DatabaseBase
3683 // @TODO: finish renaming DatabaseBase => Database